package com.weiyi.mashangzhu.Roomer.Fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.weiyi.mashangzhu.API.API;
import com.weiyi.mashangzhu.Application.MyApp;
import com.weiyi.mashangzhu.R;
import com.weiyi.mashangzhu.Roomer.Activity.LoginActivity;
import com.weiyi.mashangzhu.Roomer.Activity.MainActivity_R;
import com.weiyi.mashangzhu.Roomer.Activity.OneActivityActivity;
import com.weiyi.mashangzhu.Roomer.Activity.ThemeActivity;
import com.weiyi.mashangzhu.Roomer.Adapter.HomeHotAdapter;
import com.weiyi.mashangzhu.Roomer.Adapter.HomeThemeAdapter;
import com.weiyi.mashangzhu.Roomer.Bean.ActivityBean;
import com.weiyi.mashangzhu.Roomer.Bean.ThemeHavePageBean;
import com.weiyi.mashangzhu.Utils.LoadingDialog;
import com.weiyi.mashangzhu.Utils.SPUtils;
import com.weiyi.mashangzhu.Utils.T;
import com.weiyi.mashangzhu.Utils.UiUtil;
import com.zhy.android.percent.support.PercentLinearLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class Fragment_Main extends Fragment {
    @BindView(R.id.active)
    PercentLinearLayout active;
    @BindView(R.id.home_theme_dot)
    LinearLayout homeThemeDot;
    @BindView(R.id.home_theme_page)
    ViewPager homeThemePage;
    @BindView(R.id.home_hot_dot)
    LinearLayout homeHotDot;
    @BindView(R.id.home_hot_page)
    ViewPager homeHotPage;
    Unbinder unbinder;
    @BindView(R.id.img_head)
    ImageView imgHead;
    @BindView(R.id.no_activity)
    TextView noActivity;
    @BindView(R.id.scrollView)
    HorizontalScrollView scrollView;
    @BindView(R.id.no_theme)
    TextView noTheme;
    @BindView(R.id.no_hot)
    TextView noHot;
    private ImageView activeCollect;
    private LayoutInflater inflater;
    boolean[] flags;
    private View[] themeDots;
    private View themeCurrDot;
    private View[] hotDots;
    private View hotCurrDot;
    String imgurl = null;
    List<ActivityBean.DataBean> activitydataBeanList = new ArrayList<>();
    List<ThemeHavePageBean.DataBean.HouselistBean> themedataBeanList = new ArrayList<>();
    List<ThemeHavePageBean.DataBean.HouselistBean> hotdataBeanList = new ArrayList<>();
    List<ThemeHavePageBean.DataBean.HouselistBean> lt_theme = new ArrayList<ThemeHavePageBean.DataBean.HouselistBean>();
    int theme_clickid;

    int activityId1, activityId2, activityId3;
    private MainActivity_R mainActivity;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainActivity = (MainActivity_R) getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        unbinder = ButterKnife.bind(this, view);
        getData(0);
        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
        getData(1);
    }

    private void getData(final int a) {
        Log.e("qqqqqq", SPUtils.get(mainActivity, "token", "") + "");
        if (MyApp.ll.equals("")) {
            LoadingDialog.show(mainActivity);
        }
        //获取首页顶部图片
        OkHttpUtils.post().addParams("token", SPUtils.get(mainActivity, "token", "") + "").url(API.BaseApi_R + API.Main_ImgHead_Api).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                LoadingDialog.dismiss(mainActivity);
                T.showShort(mainActivity, "网络连接失败，请检查一下网络设置");
            }

            @Override
            public void onResponse(String response) {
                LoadingDialog.dismiss(mainActivity);
                Log.e("=========","=========");
                try {
                    JSONObject jsonobject = new JSONObject(response);
                    if (jsonobject.getInt("status") == 0) {
                        JSONObject jsonobject2 = jsonobject.getJSONObject("data");
                        imgurl = jsonobject2.getString("iUrl");
                        Glide.with(mainActivity).load(API.BaseApi_url + imgurl).error(R.mipmap.errer).into(imgHead);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
        //获取活动精选的内容
        OkHttpUtils.get().addParams("token", SPUtils.get(mainActivity, "token", "") + "")
                .url(API.BaseApi_R + API.Main_Activity_APi).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                LoadingDialog.dismiss(mainActivity);
                T.showShort(mainActivity, "网络连接失败，请检查一下网络设置");
            }

            @Override
            public void onResponse(String response) {
                Log.e("pppppp","re="+response);
                LoadingDialog.dismiss(mainActivity);
                Gson gson = new Gson();
                ActivityBean activityBean = gson.fromJson(response, ActivityBean.class);
                activitydataBeanList.clear();
                activitydataBeanList = activityBean.getData();
                List<ActivityBean.DataBean> lt = new ArrayList<ActivityBean.DataBean>();
                if (activitydataBeanList.size() >= 3) {
                    lt.add(activitydataBeanList.get(0));
                    lt.add(activitydataBeanList.get(1));
                    lt.add(activitydataBeanList.get(2));
                } else {
                    lt.addAll(activitydataBeanList);
                }

                showActive(lt,a);

            }
        });
        //获取主题房源
        OkHttpUtils.get().addParams("token", SPUtils.get(mainActivity, "token", "") + "").addParams("pagenum", 1 + "").url(API.BaseApi_R + API.Main_ThemeHouse_Api).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                LoadingDialog.dismiss(mainActivity);
                T.showShort(mainActivity, "网络连接失败，请检查一下网络设置");
            }

            @Override
            public void onResponse(String response) {
                LoadingDialog.dismiss(mainActivity);

                Gson gson = new Gson();
                themedataBeanList.clear();
                themedataBeanList = gson.fromJson(response, ThemeHavePageBean.class).getData().getHouselist();
                lt_theme.clear();
                if (themedataBeanList.size() >= 3) {
                    lt_theme.add(themedataBeanList.get(0));
                    lt_theme.add(themedataBeanList.get(1));
                    lt_theme.add(themedataBeanList.get(2));
                } else {
                    lt_theme.addAll(themedataBeanList);
                }
                Log.e("bbbbbbb", "collect0=" + lt_theme.get(0).getIsCollect());
                showTheme(lt_theme, a);

            }
        });
        //获取热门房屋
        OkHttpUtils.get().addParams("token", SPUtils.get(mainActivity, "token", "") + "").addParams("pagenum", 1 + "").url(API.BaseApi_R + API.Main_HotHouse_Api).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                LoadingDialog.dismiss(mainActivity);
                T.showShort(mainActivity, "网络连接失败，请检查一下网络设置");
            }

            @Override
            public void onResponse(String response) {
                LoadingDialog.dismiss(mainActivity);
                Gson gson = new Gson();
                hotdataBeanList = gson.fromJson(response, ThemeHavePageBean.class).getData().getHouselist();
                List<ThemeHavePageBean.DataBean.HouselistBean> lt_hot = new ArrayList<ThemeHavePageBean.DataBean.HouselistBean>();
                if (hotdataBeanList.size() >= 3) {
                    lt_hot.add(hotdataBeanList.get(0));
                    lt_hot.add(hotdataBeanList.get(1));
                    lt_hot.add(hotdataBeanList.get(2));
                } else {
                    lt_hot.addAll(hotdataBeanList);
                }
                showHot(lt_hot,a);
            }
        });

    }

    protected void hotChange(int position) {
        if (hotCurrDot != null) {
            hotCurrDot.setSelected(false);
        }

        if (hotDots != null) {
            View hotDot = hotDots[position];
            if (hotDot != null) {
                hotDot.setSelected(true);
                hotCurrDot = hotDots[position];
            }
        }
    }

    protected void themeChange(int position) {
        if (themeCurrDot != null) {
            themeCurrDot.setSelected(false);
        }
        if (themeDots!=null){
            themeDots[position].setSelected(true);
            themeCurrDot = themeDots[position];
        }
    }

    private void showActive(final List<ActivityBean.DataBean> list,int a) {
        inflater = LayoutInflater.from(mainActivity);
        if (list.size() == 0) {
            noActivity.setVisibility(View.VISIBLE);
            scrollView.setVisibility(View.GONE);
        } else {
            if (a == 0) {
            noActivity.setVisibility(View.GONE);
            scrollView.setVisibility(View.VISIBLE);
            final int size = list.size();
            flags = new boolean[size];
            for (int i = 0; i < size; i++) {
                flags[i] = false;
                View view = inflater.inflate(R.layout.item_home_active, null);
                ImageView activeImg = (ImageView) view.findViewById(R.id.active_img);
                TextView activeText = (TextView) view.findViewById(R.id.active_text);
                activeCollect = (ImageView) view.findViewById(R.id.active_collect);
                ImageView activeBtn = (ImageView) view.findViewById(R.id.active_btn);
                if (size == 1) {
                    activityId1 = activitydataBeanList.get(i).getId();
                } else if (size == 2) {
                    switch (i) {
                        case 0:
                            activityId1 = activitydataBeanList.get(i).getId();
                            break;
                        case 1:
                            activityId2 = activitydataBeanList.get(i).getId();
                            break;
                    }
                } else if (size == 3) {
                    switch (i) {
                        case 0:
                            activityId1 = activitydataBeanList.get(i).getId();
                            break;
                        case 1:
                            activityId2 = activitydataBeanList.get(i).getId();
                            break;
                        case 2:
                            activityId3 = activitydataBeanList.get(i).getId();
                            break;
                    }

                }
                if (i == size - 1) {
                    activeBtn.setVisibility(View.VISIBLE);
                    activeBtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //点击更多跳转到更多活动列表
                            UiUtil.startActivity(mainActivity, ThemeActivity.class);

                        }
                    });
                }
                    final int finalI2 = i;
                    final int finalI3 = i;
                    activeCollect.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (SPUtils.get(mainActivity, "isLogin", "0").equals("0")) {
                                UiUtil.startActivity(mainActivity, LoginActivity.class);
                            } else if (SPUtils.get(mainActivity, "isLogin", "0").equals("1")) {
                                if (list.get(finalI2).getIsCollect().equals("0")) {
                                    OkHttpUtils.get().addParams("token", SPUtils.get(mainActivity, "token", "") + "")
                                            .addParams("id", list.get(finalI2).getId() + "")
                                            .url(API.BaseApi_R + API.CollectActive_Api)
                                            .build()
                                            .execute(new StringCallback() {
                                                @Override
                                                public void onError(Request request, Exception e) {
                                                    T.showShort(mainActivity, "收藏失败");
                                                }

                                                @Override
                                                public void onResponse(String response) {

                                                    try {
                                                        JSONObject jsonObject = new JSONObject(response);
                                                        if (jsonObject.getInt("status") == 0) {
//                                                            activeCollect.setImageResource(R.mipmap.collect1);
                                                            ImageView imageView = (ImageView) active.getChildAt(finalI2).findViewById(R.id.active_collect);
                                                            imageView.setImageResource(R.mipmap.collect1);
                                                            Log.e("mmmmm","re="+response);
                                                            list.get(finalI3).setIsCollect("1");
                                                            showActive(list,1);
//                                                            getData(1);
                                                        }
                                                    } catch (JSONException e) {
                                                        e.printStackTrace();
                                                    }
                                                }
                                            });
                                } else if (list.get(finalI2).getIsCollect().equals("1")) {
                                    OkHttpUtils.get().addParams("token", SPUtils.get(mainActivity, "token", "") + "")
                                            .addParams("id", list.get(finalI2).getId() + "")
                                            .url(API.BaseApi_R + API.CollectActive_Api)
                                            .build()
                                            .execute(new StringCallback() {
                                                @Override
                                                public void onError(Request request, Exception e) {
                                                    T.showShort(mainActivity, "收藏失败");
                                                }

                                                @Override
                                                public void onResponse(String response) {

                                                    try {
                                                        JSONObject jsonObject = new JSONObject(response);
                                                        if (jsonObject.getInt("status") == 0) {
                                                            ImageView imageView = (ImageView) active.getChildAt(finalI2).findViewById(R.id.active_collect);
                                                            imageView.setImageResource(R.mipmap.collect);
                                                            Log.e("mmmmm","re2="+response);
                                                            list.get(finalI3).setIsCollect("0");
                                                            showActive(list,1);
//                                                            getData(1);
                                                        }
                                                    } catch (JSONException e) {
                                                        e.printStackTrace();
                                                    }
                                                }
                                            });
                                }
                            }
                        }
                    });
                if (list.get(i).getIsCollect().equals("0")) {
                    activeCollect.setImageResource(R.mipmap.collect);
                } else {
                    activeCollect.setImageResource(R.mipmap.collect1);
                }
                Glide.with(mainActivity).load(API.BaseApi_url + list.get(i).getAcPic()).into(activeImg);
                activeText.setText(list.get(i).getAcTitle());

                active.addView(view);
//                activeCollect.setOnClickListener(onClickListener);
                final int finalI1 = i;

//                activeCollect.setTag(i);
                final int finalI = i;
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mainActivity, OneActivityActivity.class);
                        if (size == 1) {
                            intent.putExtra("id", "" + activityId1);
                        } else if (size == 2) {
                            switch (finalI) {
                                case 0:
                                    intent.putExtra("id", "" + activityId1);
                                    break;
                                case 1:
                                    intent.putExtra("id", "" + activityId2);
                                    break;
                            }
                        } else if (size == 3) {
                            switch (finalI) {
                                case 0:
                                    intent.putExtra("id", "" + activityId1);
                                    break;
                                case 1:
                                    intent.putExtra("id", "" + activityId2);
                                    break;
                                case 2:
                                    intent.putExtra("id", "" + activityId3);
                                    break;
                            }
                        }

                        mainActivity.startActivity(intent);
                    }
                });

            }
        }
    }

    }

    private void showTheme(List<ThemeHavePageBean.DataBean.HouselistBean> list, int a) {

        if (list.size() != 0) {
            noTheme.setVisibility(View.GONE);
            if (a == 0) {
                int size = list.size() + 1;
                themeDots = new View[size];
                for (int i = 0; i < size; i++) {
                    themeDots[i] = new View(mainActivity);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(14, 14);
                    themeDots[i].setBackgroundResource(R.drawable.selector_dot_bg);
                    params.rightMargin = 18;
                    themeDots[i].setLayoutParams(params);
                    homeThemeDot.addView(themeDots[i]);

                }

                themeChange(0);
            }

            homeThemePage.setAdapter(new HomeThemeAdapter(homeThemePage, mainActivity, list));
            homeThemePage.setCurrentItem(0);
            homeThemePage.setOffscreenPageLimit(0);
            homeThemePage.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                    themeChange(position);
                }

                @Override
                public void onPageSelected(int position) {

                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
        } else {
            noTheme.setVisibility(View.VISIBLE);
        }
    }

    private void showHot(List<ThemeHavePageBean.DataBean.HouselistBean> list,int a) {
        if (list.size() != 0) {
            if (a == 0) {
                noHot.setVisibility(View.GONE);
                int size = list.size() + 1;
                hotDots = new View[size];
                for (int i = 0; i < size; i++) {
                    hotDots[i] = new View(mainActivity);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(14, 14);
                    hotDots[i].setBackgroundResource(R.drawable.selector_dot_bg);
                    params.rightMargin = 18;
                    hotDots[i].setLayoutParams(params);
                    homeHotDot.addView(hotDots[i]);
                }

                hotChange(0);
            }
            homeHotPage.setAdapter(new HomeHotAdapter(mainActivity, list));
            homeHotPage.setCurrentItem(0);

            homeHotPage.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                    hotChange(position);
                }

                @Override
                public void onPageSelected(int position) {

                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
        } else {
            noHot.setVisibility(View.VISIBLE);

        }

    }


    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (SPUtils.get(mainActivity, "isLogin", "0").equals("0")) {
                UiUtil.startActivity(mainActivity, LoginActivity.class);
            } else if (SPUtils.get(mainActivity, "isLogin", "0").equals("1")) {

                int position = (int) v.getTag();
                ImageView imageView = (ImageView) active.getChildAt(position).findViewById(R.id.active_collect);
                if (flags[position] == false) {
                    flags[position] = true;
                    imageView.setImageResource(R.mipmap.collect1);
                } else {
                    flags[position] = false;
                    imageView.setImageResource(R.mipmap.collect);
                }
            }
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
//        unbinder.unbind();
    }
}
